<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>文件列表</title>
    <!-- 引入 lucksheet 的 CSS 和 JS 资源，这里假设使用 CDN，你可以根据实际情况修改 -->
    <link rel='stylesheet' href='/luckysheet/lib/plugins/css/pluginsCss.css' />
    <link rel='stylesheet' href='/luckysheet/lib/plugins/plugins.css' />
    <link rel='stylesheet' href='/luckysheet/lib/css/luckysheet.css' />
    <link rel='stylesheet' href='/luckysheet/lib/assets/iconfont/iconfont.css' />
    <script src="/luckysheet/lib/plugins/js/plugin.js"></script>
    <script src="/luckysheet/lib/luckysheet.umd.js"></script>
    <style type="text/css">
        /* 全局样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0; /* 修改为 0，以确保没有额外的内边距 */
            background-color: #f4f4f9;
        }

        /* 顶部文件上传标题区域 */
       .upload-header {
            display: flex;
            align-items: center;
            background-color: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

       .upload-header h2 {
            margin: 0;
            color: #333;
        }

       .upload-description {
            margin-left: 20px;
            font-size: 12px;
            color: #777;
        }

        /* 文件上传和消息区域 */
       .upload-container {
            display: flex;
            gap: 20px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

       .upload-form {
            flex: 1;
        }

       .upload-form input[type="file"] {
            margin-bottom: 10px;
        }

       .upload-form input[type="submit"] {
            background-color: #007BFF;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

       .upload-form input[type="submit"]:hover {
            background-color: #0056b3;
        }

       .upload-message {
            flex: 1;
            color: #777;
        }

        /* 文件下载列表标题 */
       .download-title {
            color: #333;
            margin-bottom: 10px;
        }

        /* 文件下载列表 */
       .download-list {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

       .download-list li {
            list-style-type: none;
        }

       .download-list a {
            color: #007BFF;
            text-decoration: none;
        }

       .download-list a:hover {
            text-decoration: underline;
        }

        /* 删除按钮样式 */
       .delete-button {
            background-color: red;
            color: white;
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }

       .delete-button:hover {
            background-color: darkred;
        }

       .previewFile-button {
            background-color: rgba(86, 84, 194, 0.671);
            color: white;
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }

        /* 新增 luckysheet 容器的样式 */
        #luckysheet {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <!-- 顶部文件上传标题区域 -->
    <div class="upload-header">
        <div>
            <h2>文件上传</h2>
        </div>
        <div class="upload-description" id="miaoshu"></div>
    </div>

    <!-- 文件上传和消息区域 -->
    <div class="upload-container">
        <div class="upload-form">
            <form method="post" action="/uploadfile" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="text" name="uploadPath" placeholder="文件保存路径（可为空）">
                <input type="submit" value="上传">
                <#if uploadmessage??>
                    <p>${uploadmessage}</p>
                </#if>
            </form>
        </div>
        <div class="upload-message">
            <#if message??>
                ${message}
            </#if>
        </div>
    </div>

    <hr>

    <!-- 文件下载列表标题 -->
    <h2 class="download-title">文件下载列表</h2>

    <!-- 文件下载列表 -->
    <ul class="download-list">
        <#list files as file>
            <li>
                <a href="downloadfile/${file.name}">${file.name}</a>
                <button class="delete-button" data-file="${file.name}">删除</button>
                <button class="previewFile-button" data-filename="${file.name}">预览</button>
            </li>
        </#list>
    </ul>
    <script>
        window.addEventListener('DOMContentLoaded', function () {

            const extToMime = {
                // 图片类型
                jpg: 'image/jpeg',
                jpeg: 'image/jpeg',
                png: 'image/png',
                gif: 'image/gif',
                // PDF 类型
                pdf: 'application/pdf',
                doc: 'application/pdf',
                docx: 'application/pdf',
                // 文本类型
                sh: 'text/plain;charset=utf-8',  
                txt: 'text/plain;charset=utf-8',    // 纯文本
                html: 'text/html;charset=utf-8',       // HTML 文本
                json: 'application/json;charset=utf-8' // JSON 文本（也可归为文本处理）
                };

                
            const descriptionElement = document.getElementById('miaoshu');
            const host = window.location.host;
            const uploadInfo = `
            <br />
            <small style="font-size: 14px;">在服务器不指定上传路径 
            curl -XPOST "http://` + host + `/uploadfileapi"  -F "file=@文件路径"
            </small>
            <br />
            <small style="font-size: 14px;">在服务器指定上传路径，若为相对路径会在uploads 下创建子目录；若为绝对路径，则使用原样路径 
            <br />
            curl -XPOST "http://` + host + `/uploadfileapi"  -F "file=@文件路径"  -F "uploadPath=指定的上传路径"
            </small>
            `;

            // 将拼接好的信息赋值给 descriptionElement 的 innerHTML
            descriptionElement.innerHTML = uploadInfo;

            const deleteButtons = document.querySelectorAll('.delete-button');
            deleteButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const fileName = this.dataset.file;
                    if (confirm('确定要删除文件'+ fileName +'吗？')) {
                        const deleteUrl = 'deletefile/' + fileName;
                        fetch(deleteUrl, {
                            method: 'GET'
                        })
                           .then(response => response.text())
                           .then(data => {
                                const isContained = data.toString().includes("请输入登录账号！");
                                if (isContained) {
                                    showAutoCloseAlert("未登录，没有删除权限，请到/login页登录后再删除")
                                } else {
                                    showAutoCloseAlert(data);
                                    setTimeout(function() {
                                      window.location.reload();
                                    }, 3000);
                                          
                                };
                            });
                    };
                });
            });

            const previewFile_button = document.querySelectorAll('.previewFile-button');
            previewFile_button.forEach(button => {
                button.addEventListener('click', function () {
                    const fileName = this.dataset.filename;
                    const fileExtension = fileName.split('.').pop().toLowerCase();
                    const previewUrl = 'preview/' + fileName;
                    

                   currentAlert = showAutoCloseAlert(
					'点了一下就好了哦，再点人家就受不了', 
					{ 
						title: '等下再点了', 
						duration: 50000,
						width: 800,
						height: 800
					}
						);
                   

                    fetch(previewUrl, {
                        method: 'GET'
                    })
                   .then(response => {
                        if (!response.ok) {
                            response.text().then(text => {
                                showAutoCloseAlert( response.status + " " + text );
                                throw new Error (response.status + " " + text); 
                            }) 
                        }
                        if (fileExtension === 'xlsx' || fileExtension === 'xls'){
                        return response.json();
                        } else {
                        return response.blob();
                        }
                    })
                   .then(data => {
                        if (fileExtension === 'xlsx' || fileExtension === 'xls') {
                            const isValidData = Array.isArray(data) && data.every(item => typeof item === 'object');
                            if (!isValidData) {
                                throw new Error('数据格式不符合luckysheet要求');
                            }
                            // 假设 data 是转换后的 luckysheet 数据
                            const luckysheetDiv = document.createElement('div');
                            luckysheetDiv.id = 'luckysheet';
                            document.body.appendChild(luckysheetDiv);
                            window.luckysheet.create({
                                container: "luckysheet",
                                title: fileName,
                                lang: 'zh',
                                data: data // 假设 data 是符合 luckysheet 数据格式的数组
                            });
                        } else {
                            const mimeType = extToMime[fileExtension] || 'application/octet-stream';
                            if (mimeType === 'application/pdf') {
                             
                               // 创建Blob
                            const pdfBlob = new Blob([data], { type: mimeType });
                            const pdfUrl = URL.createObjectURL(pdfBlob);
                            // 创建包含PDF URL参数的查看器URL
                            const viewerUrl = `pdf_viewer.html?pdfUrl=`+encodeURIComponent(pdfUrl);
                            // 打开新窗口
                            const pdfnewWindow = window.open(viewerUrl, '_blank', 'width=800,height=600');
                            if (!pdfnewWindow) {
                                console.error('无法打开新窗口，请检查浏览器弹窗阻止设置');
                                URL.revokeObjectURL(pdfUrl);
                                return;
                            }

                            // 当窗口关闭时释放Blob URL
                            pdfnewWindow.addEventListener('beforeunload', () => {
                                URL.revokeObjectURL(pdfUrl);
                            });
                                                                            
                        } else {
                            const imageBlob = new Blob([data], { type: mimeType});
                            const imageUrl = URL.createObjectURL(imageBlob);
                            window.location.href = imageUrl;
                        }

                           
                        }
                    })
                   .catch(error => {
                        showAutoCloseAlert('文件预览失败，请稍后重试:'+ error.message);
                    })
                   .finally(() => {
                        currentAlert.close();
                    });
                });
            });
        });

        
        
      function showAutoCloseAlert(content, {
            title = "提示",
            duration = 3000,
            width = 280,
            height = "auto",
            position = "top-right"
        } = {}) {
            // 创建样式元素
            const styleElement = document.createElement('style');
            styleElement.textContent = `
                .auto-close-alert {
                    position: fixed;
                    background-color: #9deeaf;
                    border: 1px solid #ccc;
                    border-radius: 4px;
                    padding: 15px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    z-index: 9999;
                    transition: transform 0.3s ease, opacity 0.3s ease;
                    transform: translateY(-20px);
                    opacity: 0;
                    pointer-events: none;
                }
                .auto-close-alert.visible {
                    transform: translateY(0);
                    opacity: 1;
                    pointer-events: auto;
                }
                .alert-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 8px;
                }
                .alert-title {
                    font-weight: bold;
                    color: #333;
                }
                .close-btn {
                    cursor: pointer;
                    font-size: 18px;
                    line-height: 1;
                    color: #666;
                    transition: color 0.2s;
                }
                .close-btn:hover {
                    color: #333;
                }
                .alert-content {
                    color: #666;
                    line-height: 1.5;
                }
                .resize-handle {
                    position: absolute;
                    width: 16px;
                    height: 16px;
                    right: 0;
                    bottom: 0;
                    cursor: nwse-resize;
                    background: linear-gradient(135deg, 
                        rgba(255,255,255,0) 0%, 
                        rgba(255,255,255,0) 50%, 
                        rgba(0,0,0,0.1) 50%, 
                        rgba(0,0,0,0.1) 100%);
                }
                .top-right { top: 50px; right: 40px; }
                .top-left { top: 50px; left: 40px; }
                .bottom-right { bottom: 50px; right: 40px; }
                .bottom-left { bottom: 50px; left: 40px; }
            `;
            document.head.appendChild(styleElement);

            // 创建提示框元素
            const alertBox = document.createElement('div');
            alertBox.className = 'auto-close-alert ' + position;
            alertBox.style.width = typeof width === 'number' ? width + 'px' : width;
            alertBox.style.minHeight = typeof height === 'number' ? height + 'px' : height;
            
            // 设置提示框内容
            alertBox.innerHTML = `
                <div class="alert-header">
                    <div class="alert-title">`+ title + `</div>
                    <div class="close-btn">&times;</div>
                </div>
                <div class="alert-content">` + content + `</div>
                <div class="resize-handle"></div>
            `;
            
            // 添加到页面
            document.body.appendChild(alertBox);
            
            // 显示动画
            setTimeout(() => {
                alertBox.classList.add('visible');
            }, 10);
            
            // 关闭功能
            const closeBtn = alertBox.querySelector('.close-btn');
            closeBtn.addEventListener('click', () => {
                hideAlert();
            });
            
            // 自动关闭
            let timeoutId = setTimeout(hideAlert, duration);
            
            // 调整大小功能
            const resizeHandle = alertBox.querySelector('.resize-handle');
            let isResizing = false;
            
            resizeHandle.addEventListener('mousedown', (e) => {
                isResizing = true;
                document.body.style.cursor = 'nwse-resize';
                e.preventDefault();
            });
            
            document.addEventListener('mousemove', (e) => {
                if (!isResizing) return;
                
                // 计算新尺寸
                const newWidth = e.clientX - alertBox.getBoundingClientRect().left;
                const newHeight = e.clientY - alertBox.getBoundingClientRect().top;
                
                // 最小尺寸限制
                if (newWidth > 150) alertBox.style.width = newWidth + 'px';
                if (newHeight > 100) alertBox.style.minHeight = newHeight + 'px';
            });
            
            document.addEventListener('mouseup', () => {
                isResizing = false;
                document.body.style.cursor = '';
            });
            
            // 隐藏提示框
            function hideAlert() {
                alertBox.classList.remove('visible');
                clearTimeout(timeoutId);
                
                // 动画结束后移除元素
                setTimeout(() => {
                    document.body.removeChild(alertBox);
                    // 移除样式元素（如果是最后一个提示框）
                    const remainingAlerts = document.querySelectorAll('.auto-close-alert');
                    if (remainingAlerts.length === 0) {
                        document.head.removeChild(styleElement);
                    }
                }, 300);
            }
            
            // 鼠标悬停时暂停自动关闭
            alertBox.addEventListener('mouseenter', () => {
                clearTimeout(timeoutId);
            });
            
            // 鼠标离开时恢复自动关闭
            alertBox.addEventListener('mouseleave', () => {
                timeoutId = setTimeout(hideAlert, duration - (Date.now() - showTime));
            });
            
            const showTime = Date.now();
            
            return {
                // 提供外部主动关闭的方法
                close: hideAlert,
                // 获取当前提示框元素
                getElement: () => alertBox
            };
        }
       
   
        
        
    </script>

</body>

</html>
